<template>
  <div class="lazyshowframe" ref="lazyshowframe">
    <transition :name="transition">
      <div class="lazyshow" ref="lazyshow" v-show="lazyshow">
        <slot></slot>
      </div>
    </transition>
  </div>
</template>

<script>
import Bus from "@/assets/js/bus.js";
import { getoffsettop } from "@/assets/js/Getoffsettop.js";

export default {
  name: "lazyshow",
  data() {
    return {
      lazyshow: true,
      nowRouter: "",
      dominfo: {
        height: 0,
        offsettop: 0,
      },
    };
  },
  props: {
    transition: {
      Type: String,
      default: "fade-left",
    },
  },
  methods: {
    getheight(document) {
      let height =
        document.clientHeight +
        document.style.marginTop +
        document.style.marginBottom +
        document.style.paddingTop +
        document.style.paddingBottom;
      return height;
    },
  },
  mounted() {
    //记录当前路由
    this.nowRouter = this.$route.name;

    //渲染数据时，将空骨架代替原有的元素

    this.$refs.lazyshowframe.style.height =
      this.getheight(this.$refs.lazyshow.firstChild) + "px";
    this.dominfo.height = this.getheight(this.$refs.lazyshow.firstChild);
    this.dominfo.offsettop = getoffsettop(this.$refs.lazyshowframe);

    this.$nextTick(() => {
      this.lazyshow = false;
      //接收滚动事件
      Bus.$on("isscroll", (data) => {
        //页面真实偏移量=滚动条距离顶部距离+可视区域高度
        if (this.nowRouter == this.$route.name) {
          let scrolltop = data.scrolltop + data.clientheight;
          if (
            scrolltop > this.dominfo.offsettop + data.clientheight / 3 &&
            scrolltop < this.dominfo.offsettop + data.clientheight * 1.6
          ) {
            this.lazyshow = true;
          } else if (
            scrolltop >this.dominfo.offsettop + data.clientheight
          ) {
            this.lazyshow = false;
          } else if (scrolltop < this.dominfo.offsettop) {
            this.lazyshow = false;
          }
        }
      });
    });
  },
  beforeDestroy() {
    Bus.$off("isscroll");
  },
};
</script>

<style scoped>
</style>